<template>
  <el-collapse-item name="task">
    <div class="top" slot="title">
      <PartitionTitle title="生产任务单" type="line"></PartitionTitle>
      <el-button
        v-if="status === '1'"
        type="primary"
        size="mini"
        @click.stop="handleAdd"
        >新增</el-button
      >
    </div>
    <div>
      <div v-for="(form, i) in formData" :key="form.id" class="form-list">
        <div class="order-title">
          <span>工单{{ i + 1 }}</span>
          <el-button
            v-if="status === '1'"
            type="text"
            size="small"
            @click="handleDelete(form)"
            >取消确认</el-button
          >
        </div>
        <el-form :model="form" label-width="90px" size="small">
          <el-row>
            <el-col :span="8">
              <el-form-item label="工单编号" prop="erpOrderNo">
                <el-input
                  type="text"
                  v-model="form.erpOrderNo"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品名称" prop="itemName">
                <el-input
                  type="text"
                  v-model="form.itemName"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位" prop="itemUnit">
                <el-input
                  type="text"
                  v-model="form.itemUnit"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="计划产量" prop="planQuantity">
                <el-input
                  type="text"
                  v-model="form.planQuantity"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工单顺序" prop="orderSn">
                <el-input-number
                  v-model="form.orderSn"
                  :step="1"
                  :min="1"
                  step-strictly
                  :disabled="status == '4'"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col v-if="['2', '3'].includes(status)" :span="8">
              <el-form-item label="实际产量" prop="actualQuantity">
                <el-input
                  type="text"
                  v-model="form.actualQuantity"
                  :disabled="status === '3'"
                  @change="updateTaskStore"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="['2', '3'].includes(status)" :span="8">
              <el-form-item label="未完成数" prop="incompleteQuantity">
                <el-input
                  type="text"
                  v-model="form.incompleteQuantity"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <!-- 生产任务单弹框 -->
    <TaskBillDialog
      :visible.sync="dialogVisible"
      :defaultSearch="taskBillDefaultSearch"
      :selectableCallBack="selectableCallBack"
      @submit="handleSave"
    ></TaskBillDialog>
  </el-collapse-item>
</template>
<script>
import TaskBillDialog from "./taskBillDialog";
import { cancelOrder, confirmOrder } from "@/api/workOrder/confirmClose";
import { mapState, mapMutations } from "vuex";
export default {
  components: { TaskBillDialog },
  props: {
    // 表单状态，控制不同情况下 表单呈现的效果，1-接班，2-交班，3-历史查看，4-查看班组详情
    status: {
      type: String,
      default: "1",
    },
    detailKey: {
      type: String,
      default: "takeoverDetail",
    },
  },
  data() {
    return {
      formData: [],
      dialogVisible: false,
      selectableCallBack: (row) => {
        // 只有待确认的工单可以选择
        if (row.orderStatus != "TO_CONFIRM") {
          return false;
        }
        const index = this.formData.findIndex((ele) => ele.id == row.id);
        return index == -1;
      },
    };
  },
  computed: {
    ...mapState({
      takeoverDetail: (state) => state.turnOnDuty.takeoverDetail,
      handoverDetail: (state) => state.turnOnDuty.handoverDetail,
    }),
    detailsData() {
      return this[this.detailKey];
    },
    taskBillDefaultSearch() {
      if (!this.detailsData) {
        return {};
      }
      return {
        orderStatus: "TO_CONFIRM,TO_CLOSE",
        factoryDeptCode: this.detailsData.factoryDeptCode || null,
        workshopId: this.detailsData.workshopId || null,
        lineId: this.detailsData.lineId || null,
        groupId: this.detailsData.groupId || null,
      };
    },
  },
  mounted() {
    if (this.detailsData) {
      this.formData = this.detailsData.orderDtos || [];
    } else {
      this.formData = [];
    }
  },
  methods: {
    ...mapMutations("turnOnDuty", [
      "SET_TAKEOVER_ORDERDOTS",
      "SET_HANDOVER_ORDERDOTS",
    ]),
    handleAdd() {
      const { factoryDeptCode, workshopId, lineId, groupId } =
        this.taskBillDefaultSearch;
      if (!factoryDeptCode || !workshopId || !lineId || !groupId) {
        this.msgWarning("请选择车间/产线/班组！");
        return;
      }
      this.dialogVisible = true;
    },
    handleDelete(form) {
      this.$confirm(`是否确定取消该工单？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return cancelOrder({ id: form.id });
        })
        .then(() => {
          this.formData = this.formData.filter((ele) => ele.id !== form.id);
          this.updateTaskStore();
        })
        .catch(() => {});
    },
    updateTaskStore() {
      if (this.detailKey == "takeoverDetail") {
        this.SET_TAKEOVER_ORDERDOTS(this.formData);
      } else {
        this.SET_HANDOVER_ORDERDOTS(this.formData);
      }
    },
    handleSave(selectionList) {
      if (!selectionList?.length) {
        return;
      }
      // 查找最大的工单顺序
      let maxOrderSn = 0;
      if (this.formData?.length) {
        maxOrderSn = this.formData.reduce((prev, next) => {
          return prev.orderSn > next.orderSn ? prev.orderSn : next.orderSn;
        }, 0);
      }
      maxOrderSn++;
      // const {
      //   id,
      //   erpOrderNo,
      //   itemCode,
      //   itemName,
      //   itemUnit,
      //   planQuantity,
      //   actualQuantity,
      //   incompleteQuantity,
      // } = selectionList[0];
      const selectitem = {
        // id,
        // erpOrderNo,
        // itemCode,
        // itemName,
        // itemUnit,
        // planQuantity,
        // actualQuantity,
        // incompleteQuantity,
        ...selectionList[0],
        orderSn: maxOrderSn,
      };
      const parmas = {
        orderSn: selectitem.orderSn,
        id: selectitem.id,
        // actualStarttime: this.detailsData.workStartTime
      };
      // 生产记录ID在交班场景下需要传，接班场景不需要传
      if (this.status == "2") {
        parmas.groupProduceLogId = this.detailsData.groupProduceLogId;
      }
      confirmOrder(parmas).then((res) => {
        this.formData.push(selectitem);
        this.updateTaskStore();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.top {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 16px;
  margin: 10px 0;
}
.block-title {
  margin-bottom: 0;
}
.order-title {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  span:first-child {
    font-size: 15px;
    font-weight: bold;
    color: #409eff;
  }
}
</style>
